package com.witmore.skyline.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.common.utils.JwtUtil;
import com.jk.common.utils.PasswordUtil;
import com.witmore.skyline.db.entity.AdminDO;
import com.witmore.skyline.db.entity.OrgDO;
import com.witmore.skyline.db.entity.ProjectBusinessRefDO;
import com.witmore.skyline.db.mapper.AdminMapper;
import com.witmore.skyline.db.mapper.OrgMapper;
import com.witmore.skyline.db.mapper.ProjectBusinessRefMapper;
import com.witmore.skyline.web.controller.enums.AdminTypeEnum;
import com.witmore.skyline.web.controller.enums.WitmoreErrorCode;
import com.witmore.skyline.web.controller.vo.param.AccountLoginParamVO;
import com.witmore.skyline.web.controller.vo.result.AccountResultVO;
import com.witmore.skyline.web.controller.vo.result.AccountSession;
import com.witmore.skyline.web.controller.vo.result.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 登录接口
 * Author: 豆子高
 * Date: 2025/2/24 13:12
 */
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private ProjectBusinessRefMapper projectBusinessRefMapper;
    @Autowired
    private OrgMapper orgMapper;

    /** 登录接口 */
    @PostMapping("/login")
    @ResponseBody
    public ResponseResult<AccountResultVO> login(@RequestBody AccountLoginParamVO paramVO) {
        String password = paramVO.getPassword();
        String username = paramVO.getUsername();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ResponseResult.fail(WitmoreErrorCode.USR_NAME_PASSWORD_EMPTY);
        }
        AdminDO adminDO = adminMapper.selectOne(new QueryWrapper<AdminDO>().eq("user_name", username));
        if (adminDO == null) {
            return ResponseResult.fail(WitmoreErrorCode.USER_NOT_EXIST);
        }
        boolean checkedPassword = PasswordUtil.checkPassword(password, adminDO.getPassword());
        if (!checkedPassword) {
            return ResponseResult.fail(WitmoreErrorCode.USER_PASSWORD_ERROR);
        }
        AccountSession accountSession = new AccountSession();
        BeanUtils.copyProperties(adminDO, accountSession);
        // 项目部管理员  填充项目部信息
        if (adminDO.getAdminType() == 2) {
            List<ProjectBusinessRefDO> projectBusinessRefDOS = projectBusinessRefMapper.selectList(new QueryWrapper<ProjectBusinessRefDO>()
                    .eq("type", 3)
                    .eq("org_id", accountSession.getOrgId())
                    .eq("skyline_business_id", accountSession.getId()));
            if (CollectionUtils.isEmpty(projectBusinessRefDOS)){
                return ResponseResult.fail(WitmoreErrorCode.USER_UNBIND_PROJECT);
            }
            List<Integer> collect = projectBusinessRefDOS.stream()
                    .map(ProjectBusinessRefDO::getProjectId)
                    .collect(Collectors.toList());
            accountSession.setProjectIds(collect);
            // 由于一个用户可能属于多个项目，这个需求前端并未体现 故后端默认只接受处理第一个
            accountSession.setProjectId(collect.get(0));
        }
        String token = jwtUtil.generateToken(JSONObject.toJSONString(accountSession));
        // 封装AccountResultVO
        AccountResultVO resultVO = new AccountResultVO();
        BeanUtils.copyProperties(adminDO, resultVO);
        resultVO.setToken(token);
        resultVO.setAdminTypeName(AdminTypeEnum.getNameByCode(adminDO.getAdminType()));
        // 企业配置信息
        OrgDO orgDO = orgMapper.selectById(adminDO.getOrgId());
        resultVO.setOrgConfig(orgDO == null ? "" : orgDO.getOrgConfig());
        return ResponseResult.success(resultVO);
    }
}
